package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.merchant.MerchantEmployee;
import com.zbkj.common.model.storeclerk.StoreClerkRecord;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserMerchantCollect;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.StoreClerkPageDataBrandResponse;
import com.zbkj.common.response.StoreClerkPageDataResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.storeclerk.StoreClerk;
import com.zbkj.service.dao.StoreClerkDao;
import com.zbkj.service.service.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description StoreClerkServiceImpl 接口实现
* @date 2025-06-27
*/
@Service
public class StoreClerkServiceImpl extends ServiceImpl<StoreClerkDao, StoreClerk> implements StoreClerkService {

    @Resource
    private StoreClerkDao dao;
    @Resource
    private BrandService brandService;

    @Autowired
    private StoreClerkRecordService storeClerkRecordService;
    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserService userService;

    @Autowired
    private MerchantEmployeeService merchantEmployeeService;

    @Autowired
    private UserMerchantCollectService userMerchantCollectService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private SystemAdminService systemAdminService;


    @Override
    public Boolean create(StoreClerkSaveRequest storeClerkSaveRequest) {
        Integer curBrandId = BrandUtil.getBrandIdByUrl();
        User user = userService.getById(storeClerkSaveRequest.getUid());
        if (ObjectUtil.isNull(user)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "用户不存在");
        }
        checkExists(storeClerkSaveRequest);
        StoreClerk storeClerk = new StoreClerk();
        BeanUtils.copyProperties(storeClerkSaveRequest, storeClerk, "id");
        storeClerk.setBrandId(curBrandId);
        boolean save = save(storeClerk);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        List<StoreClerkRecord> storeClerkRecordList = new ArrayList<>();
        // 记录表
        for (Integer brandId : storeClerkSaveRequest.getBrandIdList()) {
            String name = brandService.getNameById(brandId);
            // 如果存在重复，则跳过
            if (storeClerkRecordService.existsRecord(brandId, storeClerk.getId())) {
                continue;
            }
            StoreClerkRecord storeClerkRecord = new StoreClerkRecord();
            storeClerkRecord.setStoreId(storeClerk.getId());
            storeClerkRecord.setType(1);
            storeClerkRecord.setBrandId(curBrandId);
            storeClerkRecord.setLinkBrandId(brandId);
            storeClerkRecord.setLinkBrandName(name);
            storeClerkRecordList.add(storeClerkRecord);
        }
        if (CollUtil.isNotEmpty(storeClerkRecordList)){
            storeClerkRecordService.saveBatch(storeClerkRecordList);
            // 获取到所有商户并添加店小二到这些商户里面
            for (StoreClerkRecord storeClerkRecord : storeClerkRecordList) {
                Integer systemAdminId = systemAdminService.getIdByBrandId(storeClerkRecord.getLinkBrandId());
                if (systemAdminId == null || systemAdminId <= 0) {
                    continue;
                }
                List<Merchant> merchantList = merchantService.getAllIdNameByBrandId(systemAdminId);
                List<Integer> merchantIds = merchantList.stream().map(Merchant::getId).distinct().collect(Collectors.toList());
                Boolean execute = addToMerchantEmployee(merchantIds, user);
                if (!execute) {
                    removeById(storeClerk.getId());
                }
            }
        }
        return save;
    }

    private Boolean addToMerchantEmployee(List<Integer> merchantIds, User user) {
        if (CollUtil.isEmpty(merchantIds)) {
            return true;
        }
        List<MerchantEmployee> merchantEmployeeList = new ArrayList<>();
        List<UserMerchantCollect> userCollectList = new ArrayList<>();
        merchantIds.stream().forEach(merchantId -> {
            if (!merchantEmployeeService.existsMerchantEmployee(user.getId(), merchantId)) {
                // 把用户添加到商户的员工里面
                MerchantEmployee merchantEmployee = new MerchantEmployee();
                merchantEmployee.setName(user.getNickname());
                merchantEmployee.setUid(user.getId());
                merchantEmployee.setPhone(user.getPhone());
                merchantEmployee.setRole("1,2,3,4,5,6");
                merchantEmployee.setStatus(1);
                merchantEmployee.setMerId(merchantId);
                merchantEmployee.setAvatar(user.getAvatar());
                merchantEmployeeList.add(merchantEmployee);

                addCollect(user.getId(), merchantId, userCollectList);
            }
        });

        Boolean execute = transactionTemplate.execute(e -> {
            if (CollUtil.isNotEmpty(merchantEmployeeList)) {
                merchantEmployeeService.saveBatch(merchantEmployeeList);
            }
            if (CollUtil.isNotEmpty(userCollectList)) {
                userMerchantCollectService.saveBatch(userCollectList);
            }
            return Boolean.TRUE;
        });
        return execute;
    }

    private void checkExists(StoreClerkSaveRequest storeClerkSaveRequest) {
        LambdaQueryWrapper<StoreClerk> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(StoreClerk::getUid, storeClerkSaveRequest.getUid());
        checkWrapper.eq(StoreClerk::getIsDel, 0);
        checkWrapper.eq(StoreClerk::getBrandId, BrandUtil.getBrandIdByUrl());
        long count = count(checkWrapper);
        if (count > 0) {
            throw new AppException("店小二已存在");
        }
    }

    @Override
    public Boolean createBrand(StoreClerkSaveBrandRequest storeClerkSaveRequest) {
        Integer curBrandId = BrandUtil.getBrandIdByUrl();
        User user = userService.getById(storeClerkSaveRequest.getUid());
        if (ObjectUtil.isNull(user)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "用户不存在");
        }
        checkExistsBrand(storeClerkSaveRequest.getUid());
        StoreClerk storeClerk = new StoreClerk();
        BeanUtils.copyProperties(storeClerkSaveRequest, storeClerk, "id");
        storeClerk.setBrandId(curBrandId);
        Integer brandId = BrandUtil.getBrandIdByUrl();
        if (brandId <= 0) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        List<Merchant> merchantList = merchantService.getAllIdNameByBrandId(brandId);
        if (CollUtil.isEmpty(merchantList)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "查询不到该地区下的商户");
        }
        boolean save = save(storeClerk);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        // 记录表
        addToMerchantEmployeeBrand(merchantList, storeClerk, curBrandId, user);
        return save;
    }

    private void addToMerchantEmployeeBrand(List<Merchant> merchantList, StoreClerk storeClerk, Integer curBrandId, User user) {
        List<StoreClerkRecord> storeClerkRecordList = new ArrayList<>();
        if (StrUtil.isBlank(storeClerk.getRole())) {
            storeClerk.setRole("1,2,3,4,5,6");
        }
        for (Merchant merchant : merchantList) {
            String name = merchantService.getNameById(merchant.getId());
            // 如果存在重复，则跳过
            if (storeClerkRecordService.existsRecordBrand(merchant.getId(), storeClerk.getId())) {
                continue;
            }
            StoreClerkRecord storeClerkRecord = new StoreClerkRecord();
            storeClerkRecord.setStoreId(storeClerk.getId());
            storeClerkRecord.setType(2);
            storeClerkRecord.setBrandId(curBrandId);
            storeClerkRecord.setMerchantId(merchant.getId());
            storeClerkRecord.setMerchantName(name);
            storeClerkRecordList.add(storeClerkRecord);
        }

        if (CollUtil.isNotEmpty(storeClerkRecordList)){
            List<MerchantEmployee> merchantEmployeeList = new ArrayList<>();
            List<UserMerchantCollect> userCollectList = new ArrayList<>();
            storeClerkRecordList.stream().forEach(x -> {
                if (!merchantEmployeeService.existsMerchantEmployee(user.getId(), x.getMerchantId())) {
                    // 把用户添加到商户的员工里面
                    MerchantEmployee merchantEmployee = new MerchantEmployee();
                    merchantEmployee.setName(user.getNickname());
                    merchantEmployee.setUid(user.getId());
                    merchantEmployee.setPhone(user.getPhone());
                    merchantEmployee.setRole(storeClerk.getRole());
                    merchantEmployee.setStatus(1);
                    merchantEmployee.setMerId(x.getMerchantId());
                    merchantEmployee.setAvatar(user.getAvatar());
                    merchantEmployeeList.add(merchantEmployee);

                    addCollect(user.getId(), x.getMerchantId(), userCollectList);
                }
            });

            Boolean execute = transactionTemplate.execute(e -> {
                storeClerkRecordService.saveBatch(storeClerkRecordList);

                if (CollUtil.isNotEmpty(merchantEmployeeList)) {
                    merchantEmployeeService.saveBatch(merchantEmployeeList);
                }
                if (CollUtil.isNotEmpty(userCollectList)) {
                    userMerchantCollectService.saveBatch(userCollectList);
                }
                return Boolean.TRUE;
            });
            if (!execute) {
                removeById(storeClerk.getId());
            }
        }
    }

    private void addCollect(Integer uid, Integer merchantId, List<UserMerchantCollect> userCollectList) {
        if (!userMerchantCollectService.isCollect(uid, merchantId)) {
            // 用户没有收藏店铺
            UserMerchantCollect userMerchantCollect = new UserMerchantCollect();
            userMerchantCollect.setUid(uid);
            userMerchantCollect.setMerId(merchantId);
            userCollectList.add(userMerchantCollect);
        }
    }

    private void checkExistsBrand(Integer uid) {
        LambdaQueryWrapper<StoreClerk> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(StoreClerk::getUid, uid);
        checkWrapper.eq(StoreClerk::getIsDel, 0);
        checkWrapper.eq(StoreClerk::getBrandId, BrandUtil.getBrandIdByUrl());
        long count = count(checkWrapper);
        if (count > 0) {
            throw new AppException("店小二已存在");
        }
    }

    /**
     * 分页查询店小二设置表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<StoreClerk>
     * @author dazongzi
     * @since 2025-06-27
     */
    @Override
    public List<StoreClerkPageDataResponse> getList(StoreClerkSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 StoreClerk 类的多条件查询
        LambdaQueryWrapper<StoreClerk> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(StoreClerk::getIsDel, 0);
        lambdaQueryWrapper.orderByDesc(StoreClerk::getCreateTime);
        List<StoreClerk> storeClerks = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<StoreClerkPageDataResponse> storeClerkResponses = new ArrayList<>();

        storeClerks.stream().forEach(x->{
            StoreClerkPageDataResponse storeClerkResponse = new StoreClerkPageDataResponse();
            BeanUtils.copyProperties(x, storeClerkResponse);
            storeClerkResponses.add(storeClerkResponse);
        });
        return storeClerkResponses;
    }

    /**
     * 分页查询店小二设置表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<StoreClerk>
     * @author dazongzi
     * @since 2025-06-27
     */
    @Override
    public List<StoreClerkPageDataBrandResponse> getListBrand(StoreClerkSearchBrandRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 StoreClerk 类的多条件查询
        LambdaQueryWrapper<StoreClerk> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(StoreClerk::getIsDel, 0);
        lambdaQueryWrapper.eq(StoreClerk::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.orderByDesc(StoreClerk::getCreateTime);
        List<StoreClerk> storeClerks = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<StoreClerkPageDataBrandResponse> storeClerkResponses = new ArrayList<>();

        storeClerks.stream().forEach(x->{
            StoreClerkPageDataBrandResponse response = new StoreClerkPageDataBrandResponse();
            BeanUtils.copyProperties(x, response);
            storeClerkResponses.add(response);
        });
        return storeClerkResponses;
    }

    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<StoreClerk> luw = Wrappers.lambdaUpdate();
        luw.set(StoreClerk::getIsDel, true);
        luw.in(StoreClerk::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除店小二失败"));
        }
        for (Integer storeId : idList) {
            Integer uid = getUserId(storeId);
            List<StoreClerkRecord> list = storeClerkRecordService.getIdNameList(storeId);
            if (CollUtil.isEmpty(list)) {
                continue;
            }
            for (StoreClerkRecord storeClerkRecord : list) {
                List<Integer> merchantIds = merchantService.getIdsByBrandId(storeClerkRecord.getBrandId());
                if (CollUtil.isEmpty(merchantIds)) {
                    continue;
                }
                // 删除商户里面的店员
                merchantEmployeeService.removeByUserId(uid, merchantIds);
                // 删除商户收藏
                userMerchantCollectService.deleteByUid(uid, merchantIds);
            }
        }
        return true;
    }

    private Integer getUserId(Integer id) {
        LambdaQueryWrapper<StoreClerk> lqw = Wrappers.lambdaQuery();
        lqw.select(StoreClerk::getUid);
        lqw.eq(StoreClerk::getId, id);
        return getOne(lqw).getUid();
    }

    @Override
    public boolean batchDeleteBrand(List<Integer> idList) {
        LambdaUpdateWrapper<StoreClerk> luw = Wrappers.lambdaUpdate();
        luw.set(StoreClerk::getIsDel, true);
        luw.in(StoreClerk::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除店小二失败"));
        }
        for (Integer storeId : idList) {
            Integer uid = getUserId(storeId);
            List<StoreClerkRecord> list = storeClerkRecordService.getIdNameList(storeId);
            if (CollUtil.isNotEmpty(list)) {
                List<Integer> auditIdList = list.stream().map(StoreClerkRecord::getId).distinct().collect(Collectors.toList());
                List<Integer> merchantIdList = list.stream().map(StoreClerkRecord::getMerchantId).distinct().collect(Collectors.toList());
                // 删除商户里面的店员
                merchantEmployeeService.removeByUserId(uid, merchantIdList);
                // 删除商户收藏
                userMerchantCollectService.deleteByUid(uid, merchantIdList);

                LambdaUpdateWrapper<StoreClerkRecord> luwRecord = Wrappers.lambdaUpdate();
                luwRecord.set(StoreClerkRecord::getIsDel, true);
                luwRecord.in(StoreClerkRecord::getId, auditIdList);
                update = storeClerkRecordService.update(luwRecord);
            }
        }
        return true;
    }

    /**
     * 商户入驻或新增商户自动添加到店小二
     * @param merchant
     */
    @Override
    public void regAutoAdd(Merchant merchant) {
        Integer brandId = BrandUtil.getBrandIdByUrl();
        // 最后一个店小二
        StoreClerk storeClerk = getLatest(brandId);
        if (ObjectUtil.isNotNull(storeClerk)) {
            Integer userId = storeClerk.getUid();
            // 把这个用户添加到当前的商户里面
            addUserToMerchantEmoployee(merchant.getId(), userId);
        }
    }

    private StoreClerk getLatest(Integer brandId) {
        LambdaQueryWrapper<StoreClerk> lqw = Wrappers.lambdaQuery();
        lqw.eq(StoreClerk::getIsDel, 0);
        lqw.eq(StoreClerk::getBrandId, brandId);
        lqw.orderByDesc(StoreClerk::getCreateTime);
        lqw.last("limit 1");
        StoreClerk storeClerk = getOne(lqw);
        return storeClerk;
    }

    @Override
    public boolean autoCreateBrand(StoreClerkAutoCreateBrandRequest storeClerkSaveRequest) {
        Integer curBrandId = BrandUtil.getBrandIdByUrl();
        User user = userService.getById(storeClerkSaveRequest.getUid());
        if (ObjectUtil.isNull(user)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "用户不存在");
        }
        checkExistsBrand(storeClerkSaveRequest.getUid());
        StoreClerk storeClerk = new StoreClerk();
        BeanUtils.copyProperties(storeClerkSaveRequest, storeClerk, "id");
        storeClerk.setBrandId(curBrandId);

        List<Integer> curMerchantList = storeClerkRecordService.getList(curBrandId);

        // 通过省市区选出商户，再进行分配
        List<Merchant> merchantList = merchantService.getAllIdNameExclude(BrandUtil.getBrandIdByUrl(), storeClerkSaveRequest.getProvinceId(), storeClerkSaveRequest.getCityId(), storeClerkSaveRequest.getDistrictId(), storeClerkSaveRequest.getMerNum(), curBrandId, curMerchantList);
        if (CollUtil.isEmpty(merchantList)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "查询不到该地区下的商户，或商户已被分配");
        }
        boolean save = save(storeClerk);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        addToMerchantEmployeeBrand(merchantList, storeClerk, curBrandId, user);
        return save;
    }

    private List<StoreClerk> getBrandMerchantList() {
        LambdaQueryWrapper<StoreClerk> lqw = Wrappers.lambdaQuery();
        lqw.eq(StoreClerk::getIsDel, false);
        lqw.eq(StoreClerk::getBrandId, BrandUtil.getBrandIdByUrl());
        return list(lqw);
    }

    private void addUserToMerchantEmoployee(Integer merchantId, Integer userId) {
        User user = userService.getById(userId);
        List<Integer> merchantIds = Arrays.asList(merchantId);
        addToMerchantEmployee(merchantIds, user);
    }


}

